package com.spring.jwt.token.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

/** jwt 令牌工具类
 * @author suncheng
 * @version 1.0
 * @description: TODO
 * @date 2025/5/30 10:40
 */
@Component
public class JwtUtils {

    private final SecretKey secret = Keys.secretKeyFor(SignatureAlgorithm.HS512);


    @Value("${jwt.access-token-expire}")
    private long accessExpire;

    @Value("${jwt.refresh-token-expire}")
    private long refreshExpire;

    public String generateToken(String username, long expireSeconds) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expireSeconds * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public String generateAccessToken(String username) {
        return generateToken(username, accessExpire);
    }

    public String generateRefreshToken(String username) {
        return generateToken(username, refreshExpire);
    }

    public String getUsernameFromToken(String token) {
        return Jwts.parser().setSigningKey(secret)
                .parseClaimsJws(token).getBody().getSubject();
    }

    public boolean isTokenExpired(String token) {
        try {
            Date expiration = Jwts.parser().setSigningKey(secret)
                    .parseClaimsJws(token).getBody().getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }
}
